require 'rubygems'

namespace :lite_fetion do  
  desc "lite_fetion"
  
  task :notifies => :environment do
    while(true) do
      begin
        @fetions = Fetion.all
        puts "===================================="
        puts "===get notifies from lite_fetion [#{@fetions.size}] now ..."
        puts "===================================="      
        @fetions.each_with_object([]) do |fetion,threads|
          threads << Thread.new(fetion,[LiteFetion]) do |fetion,classes|
            while true
              begin                              
                fetion.status! LiteFetion.client_state(fetion.mobile)
                if fetion.status == 'ONLINE' or fetion.status == 'NET_ERROR'
                  puts "robot.#{fetion.id} #{fetion.status}, get notifies ..."
                  fetion.notifies_from_lite_fetion!                   
                  sleep(1)
                else
                  puts "robot.#{fetion.id} #{fetion.status}, cant get notifies"
                  sleep(4)
                end
              rescue
                puts "robot.#{fetion.id} get notifies error: #{$!}:#{$@}"
                sleep(5)
              end
            end
          end
        end.each do |thread|
          thread.join
        end
        puts "===================================="
        puts ""
        puts ""
      rescue
        puts "find_fetions  error: #{$!}:#{$@}"
      end
    end
  end
end